<template>
  <div class="app-container">
    <!-- 顶部功能栏 -->
    <div class="filter-container">
      <!-- 排序方式 -->
      <el-select
        v-model="listQuery.sort"
        style="
          width: 140px;
          position: relative;
          left: 110px;
          margin-right: 20px;
        "
        class="filter-item"
        @change="handleFilter"
      >
        <el-option
          v-for="item in sortOptions"
          :key="item.key"
          :label="item.label"
          :value="item.key"
        />
      </el-select>

      <!-- 搜索方式 -->
      <el-select
        v-model="searchProperties"
        placeholder="请选择"
        class="filter-item"
        style="
          width: 100px;
          position: relative;
          left: 100px;
          margin-right: 20px;
        "
      >
        <el-option
          v-for="item in searchOptions"
          :key="item.searchvalue"
          :label="item.searchlabel"
          :value="item.searchvalue"
        />
      </el-select>
      <!-- 搜索框 -->
      <el-input
        v-model="listQuery.value"
        :placeholder="searchProperties"
        style="width: 150px; position: relative; left: 90px"
        class="filter-item"
        @keyup.enter.native="Search"
      />
      <!-- 搜索 -->
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        style="position: relative; left: 90px; margin-left: 10px"
        @click="Search"
      >
        搜索
      </el-button>

      <el-button
        class="filter-item"
        style="margin-left: 10px; position: relative; left: 90px"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        添加
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px; position: relative; left: 90px"
        type="primary"
        @click="RefreshList"
      >
        全部
      </el-button>
    </div>

    <!-- 表格主体 -->
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
      :row-style="rowStyle"
      @sort-change="sortChange"
    >
      <!-- ID -->
      <el-table-column
        label="编号"
        prop="id"
        sortable="custom"
        align="center"
        width="80"
        :class-name="getSortClass('id')"
      >
        <template slot-scope="{ row }">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <!-- 姓名 -->
      <el-table-column label="姓名" width="150px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <!-- 性别 -->
      <el-table-column label="性别" width="80px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.sex == null ? "男" : row.sex }}</span>
        </template>
      </el-table-column>
      <!-- 手机 -->
      <el-table-column label="手机" width="200px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.phone }}</span>
        </template>
      </el-table-column>
      <!-- 邮箱 -->
      <el-table-column label="邮箱" max-width="100px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.email }}</span>
        </template>
      </el-table-column>
      <!-- 职位 -->
      <el-table-column label="职位" align="center" width="120">
        <template slot-scope="{ row }">
          <span>{{ row.position }}</span>
        </template>
      </el-table-column>
      <!-- 职位偏好 -->
      <el-table-column label="职位偏好" class-name="status-col" width="280">
        <template slot-scope="{ row }">
          <div>
            {{ row.dayvalue.length == 0 ? "" : "工作日偏好 : " + row.dayvalue }}
          </div>
          <div v-for="(item, index) in row.workingTimeArr" :key="index">
            {{ `工作时间偏好${index + 1}:${item.startTime}-${item.endTime}` }}
          </div>
          <div>
            {{
              row.durationvalue == ""
                ? ""
                : "班次时长偏好 : " + row.durationvalue
            }}
          </div>
        </template>
      </el-table-column>
      <!-- 操作 -->
      <el-table-column
        label="操作"
        align="center"
        width="230"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row, $index }">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button
            v-if="row.status != 'deleted'"
            size="mini"
            type="danger"
            @click="handleDelete(row, $index)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 底部分页功能 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :size.sync="listQuery.size"
      @pagination="getList"
    />
    <!-- 编辑展示页 -->
    <transition name="el-fade-in-linear">
      <el-dialog
        :title="textMap[dialogStatus]"
        :visible.sync="dialogFormVisible"
        width="50%"
      >
        <el-form
          ref="temp"
          class="dataForm"
          :model="temp"
          label-position="left"
          :rules="rules"
          label-width="70px"
          style="width: 70%; margin-left: 50px"
        >
          <el-form-item label="姓名" prop="name">
            <el-input v-model="temp.name" style="width: 45%" />
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-radio v-model="temp.sex" label="男">男</el-radio>
            <el-radio v-model="temp.sex" label="女">女</el-radio>
          </el-form-item>
          <el-form-item label="手机" prop="phone">
            <el-input v-model="temp.phone" style="width: 45%" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input
              v-model="temp.email"
              style="width: 45%"
              :disabled="dialogStatus == 'update'"
            />
          </el-form-item>
          <el-form-item label="职位" prop="postion" class="position">
            <el-radio v-model="temp.position" label="小组长">小组长</el-radio>
            <el-radio v-model="temp.position" label="导购员">导购员</el-radio>
            <el-radio v-model="temp.position" label="库房员">库房员</el-radio>
            <el-radio v-model="temp.position" label="收银员">收银员</el-radio>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false"> 取消 </el-button>
          <el-button
            type="primary"
            @click="
              dialogStatus === 'create'
                ? DcreateData('temp')
                : DupdateData('temp')
            "
          >
            确认
          </el-button>
        </div>
      </el-dialog>
    </transition>
  </div>
</template>

<script>
import {
  fetchpersonnelList,
  createnewstaff,
  Delete,
  updateData
} from '@/api/personnel'
import { debounce } from '@/utils/MyTools'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import store from '@/store'
export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  data() {
    const Regphone = (rule, val, callback) => {
      const Reg =
        /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
      if (!Reg.test(val)) {
        callback(new Error('请输入正确的手机号'))
      }

      return callback()
    }
    const Regname = (rule, val, callback) => {
      if (val == '') {
        callback(new Error('请输入姓名'))
      }

      return callback()
    }
    const Regemail = (rule, val, callback) => {
      const Reg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if (!Reg.test(val)) {
        callback(new Error('请正确输入邮箱'))
      }

      return callback()
    }
    return {
      searchProperties: '姓名',
      dayOption: [
        {
          dayvalue: '1',
          daylabel: '1'
        },
        {
          dayvalue: '2',
          daylabel: '2'
        },
        {
          dayvalue: '3',
          daylabel: '3'
        },
        {
          dayvalue: '4',
          daylabel: '4'
        },
        {
          dayvalue: '5',
          daylabel: '5'
        },
        {
          dayvalue: '6',
          daylabel: '6'
        },
        {
          dayvalue: '7',
          daylabel: '7'
        }
      ],
      searchOptions: [
        {
          searchvalue: '姓名',
          searchlabel: '姓名'
        },
        {
          searchvalue: '职位',
          searchlabel: '职位'
        },
        {
          searchvalue: '手机号',
          searchlabel: '手机号'
        },
        {
          searchvalue: '邮箱',
          searchlabel: '邮箱'
        },
        {
          searchvalue: '性别',
          searchlabel: '性别'
        }
      ],
      durationOption: [
        {
          value: '2',
          label: '2'
        },
        {
          value: '2.5',
          label: '2.5'
        },
        {
          value: '3',
          label: '3'
        },
        {
          value: '3.5',
          label: '3.5'
        },
        {
          value: '4',
          label: '4'
        }
      ],
      TempTime: '',
      durationvalue: '',
      startTime: '',
      endTime: '',
      rowStyle: { height: '80px' },
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        // 当前页
        page: 1,
        // 每页大小
        size: 5,
        storeId: store.getters.storeId,
        key: '',
        value: '',
        sort: '+id'
      },
      sortOptions: [
        { label: 'ID 升序', key: '+id' },
        { label: 'ID 降序', key: '-id' }
      ],
      temp: {
        id: undefined,
        timestamp: new Date(),
        dayvalue: '',
        startTime: '',
        endTime: '',
        durationtime: '',
        workingTimeArr: []
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      rules: {
        phone: [{ validator: Regphone, trigger: 'blur' }],
        name: [{ validator: Regname, trigger: 'blur' }],
        email: [{ validator: Regemail, trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 根据姓名搜索
    Search() {
      switch (this.searchProperties) {
        case '姓名':
          this.listQuery.key = 'name'
          break
        case '职位':
          this.listQuery.key = 'position'
          break
        case '邮箱':
          this.listQuery.key = 'email'
          break
        case '性别':
          this.listQuery.key = 'sex'
          break
        case '手机号':
          this.listQuery.key = 'phone'
          break
      }

      this.listQuery.value = this.listQuery.value
      // 筛除无用的数据
      const datatemp = []
      datatemp.page = this.listQuery.page
      datatemp.size = this.listQuery.size
      datatemp.storeId = this.listQuery.storeId
      datatemp.value = this.listQuery.value
      datatemp.key = this.listQuery.key
      // console.log("搜索", dattemp);
      fetchpersonnelList(datatemp).then((res) => {
        if (res.returnValue == 1) {
          this.listLoading = true
          this.list = res.data.records
          this.total = res.data.total
          this.Repaint(this.list)
          this.listLoading = false
          // } else {
          //   this.$notify({
          //     title: "Error",
          //     message: res.msg,
          //     type: "error",
          //     duration: 2000,
          //   });
        }
      })
    },
    // 获取全部
    RefreshList() {
      this.listLoading = true
      // 获取用户
      const datatemp = []
      datatemp.page = 1
      datatemp.size = 5
      this.listQuery.key = '',
      this.listQuery.value = ''
      datatemp.value = this.listQuery.value
      datatemp.key = this.listQuery.key
      fetchpersonnelList(datatemp).then((res) => {
        // console.log("quanbu",res)
        if (res.returnValue == 1) {
          this.list = res.data.records
          this.total = res.data.total
          this.Repaint(this.list)
          this.listLoading = false
        } else {
          this.list = []
          this.$notify({
            title: 'Error',
            message: res.msg,
            type: 'error',
            duration: 2000
          })
        }
      })
    },
    getList() {
      this.listLoading = true
      // 获取用户
      const datatemp = []
      datatemp.page = this.listQuery.page
      datatemp.size = this.listQuery.size
      datatemp.value = this.listQuery.value
      datatemp.key = this.listQuery.key
      fetchpersonnelList(datatemp).then((res) => {
        if (res.returnValue == 1) {
          this.list = res.data.records
          this.total = res.data.total
          this.Repaint(this.list)
          this.listLoading = false
        } else {
          this.list = []
          this.$notify({
            title: 'Error',
            message: res.msg,
            type: 'error',
            duration: 2000
          })
        }
      })
    },
    Repaint(List) {
      for (var item of List) {
        // 初始化偏好数据
        item.dayvalue = ''
        item.durationvalue = ''
        item.workingTimeArr = []
        for (var StPre of item.staffPreferenceList) {
          if (StPre.preferenceName == '工作日偏好') {
            item.dayvalue = StPre.preferenceValue.split(',').sort((a, b) => {
              return a - b
            })
          } else if (StPre.preferenceName == '工作时间偏好') {
            const duration = StPre.preferenceValue.split(',')
            for (let i = 0; i < duration.length; i++) {
              const obj = { startTime: '', endTime: '' }
              obj.startTime = duration[i].split('-')[0]
              obj.endTime = duration[i].split('-')[1]
              item.workingTimeArr[i] = obj
              item.showDelet = false
            }
          } else {
            item.durationvalue = StPre.preferenceValue
          }
        }
      }
      this.listLoading = false
    },
    handleFilter(sort) {
      // 根据id排序
      let newArr = []
      if (sort == '-id') {
        newArr = this.list.sort((a, b) => {
          return parseInt(b.id) - parseInt(a.id)
        })
      } else {
        newArr = this.list.sort((a, b) => {
          return parseInt(a.id) - parseInt(b.id)
        })
      }
      this.Repaint(newArr)
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      // console.log(prop,order);
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter(this.listQuery.sort)
    },
    resetTemp() {
      this.temp = {
        storeId: '',
        name: '',
        sex: '男',
        phone: '',
        email: '',
        position: '导购员'
      }
    },
    handleCreate() {
      this.resetTemp()
      // this.$nextTick(() => {
      //   this.$refs.selectComponent.init();
      // });
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.createStaus = true
      this.$nextTick(() => {
        this.$refs['temp'].clearValidate()
      })
    },
    DcreateData: debounce(function(formName) {
      // 返回数据处理
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$confirm('是否进行创建操作?', '提示', {
            confirmButtonText: '是',
            cancelButtonText: '否',
            type: 'warning'
          })
            .then(() => {
              const returnTemp = {}
              returnTemp.storeId = store.getters.storeId
              returnTemp.name = this.temp.name
              returnTemp.sex = this.temp.sex
              returnTemp.phone = this.temp.phone
              returnTemp.email = this.temp.email
              returnTemp.position = this.temp.position
              // console.log(returnTemp)
              createnewstaff(returnTemp).then((res) => {
                if (res.returnValue == 1) {
                  this.getList()
                  this.dialogFormVisible = false
                  this.$notify({
                    title: 'Success',
                    message: '添加成功',
                    type: 'success',
                    duration: 2000
                  })
                } else {
                  this.$notify({
                    title: 'Error',
                    message: res.msg,
                    type: 'error',
                    duration: 2000
                  })
                }
              })
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: '已取消操作'
              })
            })
        }
      })
    }, 1000),
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.createStaus = false
      this.$nextTick(() => {
        this.$refs['temp'].clearValidate()
      })
    },
    // 更新操作
    DupdateData: debounce(function(formName) {
      // console.log(this.temp.sex,this.temp.position)
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$confirm('是否确认修改?', '提示', {
            confirmButtonText: '是',
            cancelButtonText: '否',
            type: 'warning'
          })
            .then(() => {
              const returnTemp = {}
              returnTemp.id = this.temp.id
              returnTemp.storeId = store.getters.storeId
              returnTemp.name = this.temp.name
              returnTemp.sex = this.temp.sex
              returnTemp.phone = this.temp.phone
              returnTemp.email = this.temp.email
              returnTemp.position = this.temp.position
              // const staffPreferenceList = this.UpdatastaffList(
              //   returnTemp,
              //   tempData
              // );
              // returnTemp.staffPreferenceList = staffPreferenceList;
              // console.log("更新后的", returnTemp);
              updateData(returnTemp).then((res) => {
                // console.log(res);
                if (res.returnValue == 1) {
                  const index = this.list.findIndex(
                    (v) => v.id === this.temp.id
                  )
                  this.list.splice(index, 1, this.temp)
                  this.dialogFormVisible = false
                  this.$notify({
                    title: 'Success',
                    message: res.msg,
                    type: 'success',
                    duration: 2000
                  })
                } else {
                  this.$notify({
                    title: 'Error',
                    message: res.msg,
                    type: 'error',
                    duration: 2000
                  })
                }
              })
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: '已取消修改'
              })
            })
        }
      })
    }, 500),
    handleDelete(row, index) {
      this.$confirm('此操作将永久删除该员工信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          Delete(row.id).then((res) => {
            if (res.returnValue == 1) {
              this.$notify({
                title: 'Success',
                message: '删除成功',
                type: 'success',
                duration: 2000
              })
              this.list.splice(index, 1)
              this.total = this.list.length
            } else {
              this.$notify({
                title: 'Error',
                message: res.msg,
                type: 'error',
                duration: 2000
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
<style lang="less">
.app-container {
  height: 90vh;
  overflow-y: scroll;
}
//消除页面滚动条
::-webkit-scrollbar {
  overflow: hidden hidden;
}
.filter-container {
  display: flex;
  justify-content: flex-start;
}
.dataForm {
  width: 100%;
  height: 100%;
  // border: 1px solid black;
}
.flex {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 10px;
  width: 100%;
  // border: 1px solid black;
}
.workTimePre {
  width: 100%;
  // border: 1px solid black;
}
.preference {
  width: 120%;
  transform: translateY(30%);
  // border: 1px solid black;
}

.Itemtitle {
  display: block;
  width: 30%;
  height: 10%;
  // padding: 10px 10px 10px 0;
  margin-right: 20px;
  // border: 1px solid black;
}
.position {
  width: 150%;
}
</style>
